package com.example.blogserver.service.Impl;

import com.example.blogserver.service.ListService;
import com.example.blogserver.mapper.UserMapper;
import com.example.blogserver.pojo.User;
import com.example.blogserver.a_utils.Constant;
import com.example.blogserver.a_utils.GetBean;
import com.example.blogserver.a_utils.ResponseBodyMessage;
import com.example.blogserver.service.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@SuppressWarnings({"all"})
@Service
public class UpdateServiceImpl implements UpdateService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private static RedisTemplate redisTemplate = (RedisTemplate) GetBean.getBean("redisTemplate");

    @Autowired
    private ListService listService;

    //获取配置文件当中配置的上传路径
    @Value("${upload.myphotopath}")
    private String dirPath;

    /**
     * 对信息进项校验并修改数据库
     */
    @Override
    public ResponseBodyMessage<Boolean> updateMessage(HttpServletRequest request,
                                                      String uname, String usig,
                                                      String upas1, String upas2, String uoldPas,
                                                      String ucode, String uemail, String ugitee) {
        ResponseBodyMessage responseBodyMessage = new ResponseBodyMessage();
        //响应默认给定初始值,当校验全部通过替换,否则只修改Message
        responseBodyMessage.setStatus(-1);
        responseBodyMessage.setData(false);
        //获取登录用户的账号ID
        User user = listService.queryByAccount(request).getData();
        String userId = user.getUserid();
        //传参进行修改
        User newUser = new User();//修改的临时封装体
        //校验重置密码
        if (!upas1.equals("") && !upas2.equals("")){
            if (!upas1.equals(upas2)){
                responseBodyMessage.setMessage("确认密码和修改密码不一致~");
                return responseBodyMessage;
            }
            String Pas = bCryptPasswordEncoder.encode(upas1);
            newUser.setPassword(Pas);
        }
        //对旧密码进行校验
        if (!uoldPas.equals("")){
            String checkPas = user.getPassword();
            Boolean flg = bCryptPasswordEncoder.matches(uoldPas,checkPas);
            if (flg == false){
                //密码错误
                responseBodyMessage.setMessage("原始密码错误，请重新输入~");
                return responseBodyMessage;
            }
        }
        //对输入的邮箱信息进行校验
        //对验证码进行验证
        if (!uemail.equals("") && !ucode.equals("")){
            String checkEmail = (String) request.getSession(false).getAttribute("emailId");
            if (checkEmail == null){
                responseBodyMessage.setMessage("您还未发送验证码~");
                return responseBodyMessage;
            }else {
                if (!checkEmail.equals(uemail)){
                    responseBodyMessage.setMessage("邮箱信息与原始验证邮箱不一致~");
                    return responseBodyMessage;
                }
                //判断Redis中是否含有key（过期）
                Boolean ret = redisTemplate.hasKey(checkEmail);
                if (ret == false){
                    //验证码过期
                    responseBodyMessage.setMessage("验证码过期，请重新发送验证码");
                    return responseBodyMessage;
                }else {
                    //在Redis当中获取存储的value
                    String checkCode = (String) redisTemplate.opsForValue().get(checkEmail);
                    if (!checkCode.equals(ucode)){
                        responseBodyMessage.setMessage("验证码有误，请检查验证码后输入~");
                        return responseBodyMessage;
                    }
                }
                //判断邮箱是否使用过
                User check = userMapper.queryUser(uemail);
                if (check != null){
                    //邮箱被使用过
                    responseBodyMessage.setMessage("该邮箱已经被绑定，不可重复绑定多个账号~");
                    return responseBodyMessage;
                }
                //重置邮箱校验通过
                newUser.setEmail(uemail);
            }
        }
        newUser.setGitee(ugitee);
        newUser.setSignature(usig);
        newUser.setUsername(uname);
        newUser.setUserid(userId);
        int result = userMapper.updateUserInfo(newUser);
        if (result == 1){
            //修改成功，移除session会话当中存储的邮箱信息
            String Email = (String) request.getSession(false).getAttribute("emailId");
            if (Email != null){
                request.getSession(false).removeAttribute("emailId");
            }
            responseBodyMessage.setStatus(1);
            responseBodyMessage.setMessage("修改个人信息成功~");
            responseBodyMessage.setData(true);
            return responseBodyMessage;
        }else {
            responseBodyMessage.setMessage("系统故障,修改失败~");
            return responseBodyMessage;
        }
    }

    @Override
    public ResponseBodyMessage<Boolean> uploadMyPhoto(MultipartFile file, HttpServletRequest request) {
        ResponseBodyMessage<Boolean> responseBodyMessage = new ResponseBodyMessage<>();
        //获取Session当中存储的用户信息
        String account = (String) request.getSession(false).getAttribute(Constant.USERINFO_SESSION_KEY);
        //判断是否使用邮箱登录
        if (account.indexOf('@') != -1){
            account = listService.queryByAccount(request).getData().getUserid();
        }
        //获取数据库当中的用户信息
        User user = listService.getUserByEamil(account);
        //获取原始的文件名称
        String oldPath = user.getImg();
        String oldFileName = oldPath.substring(8);//获取旧的文件名
        oldPath = dirPath + oldFileName;//旧的本地文件全名
        //对旧的文件进行处理-》删除
        File dest = new File(oldPath);
        if (!oldFileName.equals("DEFAULT.PNG")){
            //如果是默认头像，则不进行删除，后续新用户仍然使用旧头像
            boolean delete = dest.delete();
        }
        //上传文件路径
        String fileNameAndType = file.getOriginalFilename();//获取文件类型 XXX.JPG XXX.PNG
        if (fileNameAndType.equals("") || fileNameAndType == null){
            responseBodyMessage.setStatus(-1);
            responseBodyMessage.setMessage("文件上传失败，请先检查文件是否合法");
            responseBodyMessage.setData(false);
            return responseBodyMessage;
        }
        int index = fileNameAndType.lastIndexOf(".");//获取最后一个点的位置
        String title = fileNameAndType.substring(index);//获取文件后缀名 .jpg .png
        //生成动态文件名
        String fileName = UUID.randomUUID() + title;//生成唯一文件标识名
        //对新文件进行上传
        String uploadPath = dirPath + fileName;
        try {
            file.transferTo(new File(uploadPath));
            //对数据库进行修改
            String changePath = "./image/" +fileName;
            userMapper.updateImage(changePath,account);
            responseBodyMessage.setStatus(1);
            responseBodyMessage.setMessage("头像上传成功");
            responseBodyMessage.setData(true);
        }catch (IOException e){
            responseBodyMessage.setMessage("头像上传失败");
            responseBodyMessage.setStatus(-1);
            responseBodyMessage.setData(false);
            e.printStackTrace();
        }
        return responseBodyMessage;
    }
}
